package com.example.personalcenter;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.personalcenter.adapter.MyListAdapter;
import com.example.personalcenter.databinding.ActivityHomeBinding;
import com.example.personalcenter.model.MyItem;
import com.example.personalcenter.model.UserViewModel;

public class HomeActivity extends AppCompatActivity {

    private ActivityHomeBinding binding;
    private UserViewModel vm;
    private MyListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        vm = new ViewModelProvider(this).get(UserViewModel.class);
        adapter = new MyListAdapter();
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(adapter);

        // 下拉刷新
        binding.btnRefresh.setOnClickListener(v -> vm.loadItems());

        // 点击跳转详情
        adapter.setOnItemClickListener(item -> {
            Intent intent = new Intent(this, DetailActivity.class);
            intent.putExtra("title", item.getTitle());
            intent.putExtra("desc", item.getDesc());
            startActivity(intent);
        });

        // 长按删除
        adapter.setOnItemLongClickListener(item -> {
            vm.deleteItem(item);
            return true;
        });

        // 数据观察
        vm.getItems().observe(this, items -> {
            adapter.setData(items);
        });

        // 首次加载
        vm.loadItems();

        // 底部导航
        findViewById(R.id.nav_home).setOnClickListener(v -> {});
        findViewById(R.id.nav_profile).setOnClickListener(v -> {
            startActivity(new Intent(this, ProfileEditActivity.class));
        });
    }
}